package com.example.miniomultipartupload.controller;

import com.example.miniomultipartupload.domain.bo.MultipartInitBO;
import com.example.miniomultipartupload.domain.param.MultipartCompleteParam;
import com.example.miniomultipartupload.domain.param.MultipartInitParam;
import com.example.miniomultipartupload.service.IMultipartService;
import com.example.miniomultipartupload.util.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Objects;

/**
 * 流程  init -> chunkUpload -> complete
 *
 * 已上传过的文件秒传（文件名+文件大小+bucket   是一样的表示同一个文件）
 *
 * 24小时内可以断点续传（生成的chunkUpload有效期是24小时，redis中 MULTIPART_UPLOADID_KEY和MULTIPART_UPLOADID_CHUNK_KEY有效期是24小时）
 * 超过24小时均失效
 *
 * 所有的chunkUpload调用成功后，调用complete； chunkUpload未都调用成功时调用complete会返回500
 */
@Api( tags = "分片上传")
@RestController
@RequestMapping("multipart")
public class MultipartController {
    @Autowired
    private IMultipartService multipartService;

    @ApiOperation(value = "分片初始化", httpMethod = "POST",notes = "分片上传，分片大小为10兆")
    @PostMapping("init")
    public AjaxResult initMultiPartUpload(@RequestBody MultipartInitParam requestParam) {

        final MultipartInitBO multipartInitBO = multipartService.initMultiPartUpload(requestParam);
        if(Objects.nonNull(multipartInitBO)){
            return AjaxResult.success(multipartInitBO);
        }else{
            return AjaxResult.error("初始化分片失败");
        }
    }

    @ApiOperation(value = "分片上传", httpMethod = "POST", notes = "由uploadId和chunk查到minio生成的分片url, 上传文件part到minio")
    @PostMapping("/chunkUpload")
    public AjaxResult chunkUpload(@RequestPart("file") MultipartFile file, @RequestParam("uploadId")String uploadId, @RequestParam("chunk")String chunk){
        String msg = multipartService.chunkUpload(file, uploadId, chunk);
        return msg == null ? AjaxResult.success() : AjaxResult.error(msg);
    }

    @ApiOperation(value = "完成上传", httpMethod = "PUT",notes = "当所有分片上传接口返回200后，调用此方法，合并分片（minio文件服务器合并），完成上传。")
    @PutMapping("complete")
    public AjaxResult completeMultiPartUpload(@RequestBody MultipartCompleteParam param) {

        String fileAddress = multipartService.mergeMultipartUpload(param);

        return fileAddress == null ? AjaxResult.error() : AjaxResult.success(fileAddress);
    }
}
